package com.tanhua.user.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserFreezeApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.pojo.UserFreeze;
import com.tanhua.user.mapper.UserInfoMapper;
import com.tanhua.user.mapper.UserMapper;
import com.tanhua.user.pojo.User;
import com.tanhua.user.pojo.UserInfo;
import com.tanhua.user.vo.PageResult;
import com.tanhua.user.vo.UserInfoVo;
import com.tanhua.user.vo.UserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private UserFreezeApi userFreezeApi;

    public PageResult getUserData(Integer pagesize, Integer page, Integer id, String nickname, String city) {
        PageResult pageResult = new PageResult();
        Page<UserInfo> infoPage = null;
        ArrayList<UserVo> userVos = null;
        try {
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            //封装条件
            if (null!=id){
                queryWrapper.eq("user_id",id);
            }
            if (StringUtils.isNotBlank(nickname)){
                queryWrapper.eq("nick_name",nickname);
            }
            if (StringUtils.isNotBlank(city)){
                queryWrapper.like("city",city);
            }

            infoPage = new Page<>(page,pagesize);
            userInfoMapper.selectPage(infoPage,queryWrapper);

            List<UserInfo> infoList = infoPage.getRecords();

            //拿到所有的ids
            List<Long> idss = infoList.stream().map(UserInfo::getUserId).collect(Collectors.toList());
            ArrayList<Integer> ids = new ArrayList<>();
            for (Long longId : idss) {
                ids.add(longId.intValue());
            }
            QueryWrapper<User> idsWrapper = new QueryWrapper<>();
            idsWrapper.in("id",ids);

            List<User> users = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(ids)){
                users = userMapper.selectList(idsWrapper);
            }
            Map<Integer, String> map = null;

            try {
                //查询用户冻结状态
                map = new HashMap<>();

                for (Integer userId : ids) {
                    String key = "freezeUser_"+userId;
                    String value = redisTemplate.opsForValue().get(key);

                    ObjectMapper objectMapper = new ObjectMapper();
                    UserFreeze freeze = objectMapper.readValue(value, UserFreeze.class);
                    if (null!=freeze&&freeze.getFreezingTime()>System.currentTimeMillis()){
                        map.put(userId,"2");
                    }
                    if (null!=freeze&&freeze.getFreezingTime()<=System.currentTimeMillis()){
                        map.put(userId,"1");
                    }
                    if (StringUtils.startsWith(value,"reasonsForThawing_")){
                        map.put(userId,"1");
                    }
                }
            } catch (Exception e) {
                map = userFreezeApi.findFreezeStatueByIds(ids);
            }

            //得到所有用户的最后活跃时间

            Map<Integer, Long> userLastTime = userFreezeApi.findUserLastTimeByIds(ids);

            //封装pageResult
            userVos = new ArrayList<>();

            for (UserInfo userInfo : infoList) {
                UserVo userVo = new UserVo();
                userVo.setId(userInfo.getUserId().intValue());
                userVo.setLogo(userInfo.getLogo());
                userVo.setLogoStatus(userFreezeApi.findFreezeStatue(Integer.parseInt(userInfo.getUserId().toString())) ? "2" : "1");
                userVo.setNickname(userInfo.getNickName());

                for (User user : users) {
                    if (user.getId().equals(userInfo.getUserId())){
                        userVo.setMobile(user.getMobile());
                    }
                }

                userVo.setSex(userInfo.getSex().toString());
                userVo.setAge(userInfo.getAge());
                userVo.setOccupation(userInfo.getIndustry());

                String statue = map.get(Math.toIntExact(userInfo.getUserId()));
                if (StringUtils.isNotBlank(statue)){
                    userVo.setUserStatus(statue);
                }else {
                    userVo.setUserStatus("1");
                }

                Long aLong = userLastTime.get((userInfo.getUserId().intValue()));

                if (aLong!=null){
                    userVo.setLastActiveTime(aLong);//TODO
                }else {
                    userVo.setLastActiveTime(1619614135245L);//TODO
                }

                userVo.setCity(userInfo.getCity());

                userVos.add(userVo);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        pageResult.setItems(userVos);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

        if (infoPage != null){
            pageResult.setCounts((int) infoPage.getTotal());
            pageResult.setPages((int) infoPage.getPages());
        }

        return pageResult;
    }


    public UserInfoVo getUserInfoVo(String userID) {
        LambdaQueryWrapper<User> queryWrapperUser = new LambdaQueryWrapper<>();
        queryWrapperUser.eq(User::getId, userID);
        User user = userMapper.selectOne(queryWrapperUser);

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, userID);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(user.getId().intValue());

        Map<Integer, Long> userLastTime = userFreezeApi.findUserLastTimeByIds(ids);

        //封装
        UserInfoVo infoVo = new UserInfoVo();
        infoVo.setId(userInfo.getUserId().intValue());
        infoVo.setNickname(userInfo.getNickName());
        infoVo.setMobile(user.getMobile());
        infoVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
        infoVo.setPersonalSignature("这是自定义的个性签名～～");
        infoVo.setAge(userInfo.getAge());

        infoVo.setCountLiked(userLikeApi.getLikeCount(Long.valueOf(userID)));
        infoVo.setCountBeLiked(userLikeApi.getLikedCount(Long.valueOf(userID)));
        infoVo.setCountMatching(userLikeApi.getMatchCount(Long.valueOf(userID)));

        Long aLong = userLastTime.get((userInfo.getUserId().intValue()));

        if (aLong!=null){
            infoVo.setLastActiveTime(aLong);
        }else {
            infoVo.setLastActiveTime(1619614135245L);
        }


        //查询冻结状态
        try {
            String key = "freezeUser_" + Integer.parseInt(userID);
            String value = redisTemplate.opsForValue().get(key);
            ObjectMapper objectMapper = new ObjectMapper();
            UserFreeze freeze = objectMapper.readValue(value, UserFreeze.class);

            if (null!=freeze&&freeze.getFreezingTime()>System.currentTimeMillis()){
                infoVo.setUserStatus("2");//1正常,2冻结
            }
            if (null!=freeze&&freeze.getFreezingTime()<=System.currentTimeMillis()){
                infoVo.setUserStatus("1");//1正常,2冻结
            }
            if (StringUtils.startsWith(value,"reasonsForThawing_")){
                infoVo.setUserStatus("1");//1正常,2冻结
            }

        } catch (Exception e) {
            infoVo.setUserStatus(userFreezeApi.findFreezeStatue(Integer.parseInt(userID)) ? "2" : "1");//1正常,2冻结
        }

        infoVo.setIncome(Integer.parseInt(userInfo.getIncome()));
        infoVo.setOccupation(userInfo.getIndustry());
        infoVo.setCreated((int) userInfo.getCreated().getTime());
        infoVo.setCity(userInfo.getCity());
        infoVo.setLogo(userInfo.getLogo());
        infoVo.setTags(userInfo.getTags());

        return infoVo;
    }


    public String freezeUser(UserFreeze userFreeze) {

        //存到redis中
        try {
            String key = "freezeUser_"+userFreeze.getUserId().toString();
            Long day = userFreeze.getFreezingTime();
            long freezing = 0;
            if (day == 1) {
                freezing = System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000;
            }
            if (day == 2) {
                freezing = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000;
            }
            if (day == 3) {
                freezing = System.currentTimeMillis() << 2;
            }
            userFreeze.setFreezingTime(freezing);
            userFreeze.setLogTime(System.currentTimeMillis());
            String value = new ObjectMapper().writeValueAsString(userFreeze);
            redisTemplate.opsForValue().set(key,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        //再存到mongodb
        Boolean res = userFreezeApi.freezeUser(userFreeze);
        if (res) {
            return "操作成功";
        }
        return "操作失败";
    }

    public String unfreezeUser(Integer userId, String reasonsForThawing) {
        //存到redis中
        String key = "freezeUser_" + userId;
        String value = "reasonsForThawing_"+reasonsForThawing;
        redisTemplate.opsForValue().set(key, value);

        //再存到mongodb
        Boolean res = userFreezeApi.unfreezeUser(userId, reasonsForThawing);
        if (res) {
            return "操作成功";
        }
        return "操作失败";
    }

}
